package org.fixed.dubboconsumer.core.util;

import org.fixed.dubboconsumer.config.DubboCallProperties;
import org.fixed.dubboconsumer.entity.CallRequest;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;

/**
 * @author [xuzhongwei]
 * @see [相关类/方法]
 * @since 2019/8/22
 */
@Component
public class DubboCallUtil {

    @Autowired
    private DubboCallProperties dubboCallProperties;

    private static DubboCallProperties properties;

    @PostConstruct
    public void init() {
        properties = dubboCallProperties;
    }

    /**
     * 不同模式执行
     */
    private static Map<String, Call> call = new HashMap<>();

    /**
     * 执行相关方法
     *
     * @param request
     * @param method
     * @return
     */
    public static Object call(CallRequest request, Method method) {
        return getCall(request).invoke(request, method);
    }

    /**
     * 获取执行器
     *
     * @param request
     * @return
     */
    private static Call getCall(CallRequest request) {
        String key = getKey(request.getModel(), StringUtils.defaultIfEmpty(request.getRemoteUrl(), properties.getProperties().get(request.getModel()).getRemoteUrl()));
        if (null != call.get(key)) {
            return call.get(key);
        } else {
            return initCallConfig(key, properties.getProperties().get(request.getModel()), request);
        }
    }

    /**
     * 初始化多个配置
     *
     * @param key
     * @param config
     * @param request
     * @return
     */
    private static Call initCallConfig(String key, DubboCallProperties.Config config, CallRequest request) {
        //直连地址
        String remoteUrl = "";
        if (StringUtils.equals(request.getModel(), "dev")) {
            remoteUrl = StringUtils.defaultIfEmpty(request.getRemoteUrl(), config.getRemoteUrl());
        }
        Call callbackUtil = new Call(config.getRegistryAddress(), remoteUrl, key);
        call.put(key, callbackUtil);
        return callbackUtil;
    }

    /**
     * 获取不同模式下，不同直连地址的key
     *
     * @param model
     * @param remoteUrl
     * @return
     */
    private static String getKey(String model, String remoteUrl) {
        if (StringUtils.equals(model, "dev")) {
            if (StringUtils.isNotBlank(remoteUrl)) {
                remoteUrl = remoteUrl.replaceAll("https", "").replaceAll("http", "").replaceAll(":", "")
                        .replaceAll("/", "").replaceAll(".", "");
            }
            return model + remoteUrl;
        }
        return model;
    }

}
